import {
	reactive,
	ref
} from "vue"
import {
	getShopDetail,
	getShopPage
} from "@/config/api/shop"
import utils from "../utils/utils"

const useShop = () => {
	const shopList = ref([])
	const currentShop = ref({});
	const listParams = reactive({
		searchKey: '',
		pageNum: 1,
		pageSize: 15,
		total: 0,
		lng: 0,
		lat: 0
	})
	const getShopList = async () => {
		try {
			await getCurrentLocation();
			const res = await getShopPage(listParams)
			if (res.code == 200) {
				shopList.value = shopList.value.concat(res.rows);
				listParams.total = res.total;
			}
		} catch (e) {
			//TODO handle the exception
		}
	}
	const resetList = () => {
		shopList.value = []
		listParams.pageNum = 1
		getShopList()
	}
	const chooseShop = (shop) => {
		uni.setStorageSync('shopId', shop.id)
		uni.navigateBack()
	}
	const getCurrentShop = async () => {
		try {
			const shopId = uni.getStorageSync('shopId') || null;
			const res = await getShopDetail({
				lng: listParams.lng,
				lat: listParams.lat,
				shopId
			})
			if (res.code == 200) {
				currentShop.value = res.data
			}
		} catch (e) {
			//TODO handle the exception
		}
	}
	//获取当前位置
	const getCurrentLocation = () => {
		return new Promise((resolve, reject) => {
			// #ifndef MP-WEIXIN
			jWeixin.getLocation({
				type: 'gcj02',
				success: (res) => {
					listParams.lng = res.longitude
					listParams.lat = res.latitude
					resolve();
				},
				fail: (err) => {
					utils.showToast('获取位置失败')
					console.log(err);
					reject(err)
				}
			})
			// #endif
			// #ifdef MP-WEIXIN
			uni.getLocation({
				type: 'gcj02',
				success: (res) => {
					listParams.lng = res.longitude
					listParams.lat = res.latitude
					resolve();
				},
				fail: (err) => {
					utils.showToast('获取位置失败')
					console.log(err);
					reject(err)
				}
			})
			// #endif
		});
	}
	return {
		shopList,
		currentShop,
		getShopList,
		resetList,
		listParams,
		chooseShop,
		getCurrentShop
	}
}
export default useShop